/**
 * Copyright (C), 2023-2033
 */
package com.goaly.gpt;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dashscope.conversation.Conversation;
import com.alibaba.dashscope.conversation.ConversationResult;
import com.alibaba.dashscope.conversation.qwen.QWenConversationParam;
import groovy.lang.Tuple2;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 通义千问测试代码生成器
 *
 * @author: lys
 * @date: 2023/6/19 22:31
 */
public class QwenTestCodeGenerator implements TestCodeGenerator {

    /**
     * 测试代码生成中标记
     */
    private final static AtomicBoolean TEST_CODE_GENERATING = new AtomicBoolean(false);

    @Override
    public Tuple2<String, String> getCode(String className, String methodText) {
        if (TEST_CODE_GENERATING.get()) {
            throw new IllegalStateException("正在生成单元测试代码，请稍后再试。");
        }
        String testCode = StrUtil.EMPTY, resultText;
        if (StrUtil.isBlank(methodText)) {
            return new Tuple2<>(testCode, "方法体为空");
        }
        try {
            String simpleClassContent = getSimpleClassContent(className, methodText);
            Conversation conversation = new Conversation();
            QWenConversationParam param =
                    QWenConversationParam.builder()
                            .model(QWenConversationParam.QWEN_V1)
                            .prompt(simpleClassContent)
                            .build();

            // 直接调用接口
            // 如果正常返回即可以直接使用
            // 否则会抛出ApiException异常，检查e.getStatus()即可拿到错误信息
            ConversationResult result = conversation.call(param);
            resultText = result.getMessage().getPayload();
            if (StrUtil.isNotBlank(resultText)) {
                System.out.println("GPT接口返回:\n" + resultText);
                int startIndex = resultText.indexOf(CODE_MARK);
                if (startIndex > -1) {
                    // 找到CODE_MARK之后第一个换行符，截取到最后一个CODE_MARK之前
                    startIndex = resultText.indexOf(StrUtil.LF, startIndex + 1);
                    testCode = resultText.substring(startIndex + 1, resultText.lastIndexOf(CODE_MARK));

                    if (testCode.lastIndexOf(CODE_MARK) > -1) {
                        // 如果还有CODE_MARK，取最后一个代码块
                        testCode = testCode.substring(testCode.lastIndexOf(CODE_MARK));
                    }
                }
            }
        } finally {
            TEST_CODE_GENERATING.set(false);
        }

        return new Tuple2<>(testCode, resultText);
    }
}